package service

import (
	"fmt"
	"ksd-social-api/commons/base/service"
	"ksd-social-api/commons/page"
	context3 "ksd-social-api/modules/msg/model/context"
	nvo "ksd-social-api/modules/note/model/vo"
	"ksd-social-api/modules/special/model"
	"ksd-social-api/modules/special/model/context"
	"ksd-social-api/modules/special/model/vo"
	"ksd-social-api/utils"
	"ksd-social-api/utils/rdb"
	"strconv"
	"time"
)

type AdminSpecialService struct {
	service.BaseService
}

/**
 * @author feige
 * @date 2023-10-13
 * @version 1.0
 * @desc 查询资源列表信息，栏目和搜索使用
 */
func (service *AdminSpecialService) FindSpecialListAndPage(ctx context.SpecialSearchContext) *page.Page {
	p := adminSpecialMapper.FindSpecialListAndPage(ctx)
	specials := p.Records.([]model.Special)
	specialVos := []vo.SpecialVo{}
	for _, special := range specials {
		// 3: 查询当前登录的用户信息和资源id去查询用户资源收藏表
		specialVo := vo.SpecialVo{}
		utils.CopyProperties(&specialVo, special)
		// 2: 如果没有错误就必须把model数据导入vo数据中
		specialVos = append(specialVos, specialVo)
	}

	p.Records = specialVos
	return p
}

/**
 * @author feige
 * @date 2023-10-08
 * @desc 根据id查询资源信息的业务蹭
 */
func (service *AdminSpecialService) GetSpecialById(specialId uint64, userId uint64, systemId uint64) (pvo *vo.SpecialDetailVo, err error) {
	specialDetailVo := vo.SpecialDetailVo{}
	// 1: 根据id查询数据层
	special, err := specialMapper.GetById(specialId, systemId)
	if err != nil {
		return nil, err
	}
	utils.CopyProperties(&specialDetailVo, special)
	// 绑定明细
	specialDetailVo.BindList, _ = service.FindAdminSpecialBindsAll(special.Id, userId, systemId, false)
	// 绑定学生
	specialDetailVo.Students = service.FindSpecialStudents(special.Id, systemId)
	// 章绑定节
	return &specialDetailVo, err
}

/**
 * @author feige
 * @date 2023-10-08
 * @desc 根据id查询资源信息的业务蹭
 */
func (service *AdminSpecialService) GetSpecialByIdNo(specialId uint64, systemId uint64) (pvo *vo.SpecialDetailVo, err error) {
	specialDetailVo := vo.SpecialDetailVo{}
	// 1: 根据id查询数据层
	special, err := specialMapper.GetById(specialId, systemId)
	if err != nil {
		return nil, err
	}
	utils.CopyProperties(&specialDetailVo, special)
	// 章绑定节
	return &specialDetailVo, err
}

func (service *AdminSpecialService) FindSpecialStudents(specialId uint64, systemId uint64) []vo.UserBuySpecialStudentVo {
	userBuyStudents, _ := specialBuyMapper.FindSpecialUserBuyStudents(specialId, systemId)
	var studentsVos []vo.UserBuySpecialStudentVo
	for _, userBuyStudent := range userBuyStudents {
		var studentsVo vo.UserBuySpecialStudentVo
		utils.CopyProperties(&studentsVo, userBuyStudent)
		studentsVos = append(studentsVos, studentsVo)
	}
	return studentsVos

}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  修改状态
 */
func (service *AdminSpecialService) UpdateFieldById(ctx context.SpecialUpdateContext) bool {
	return adminSpecialMapper.UpdateFieldById(ctx.Id.Uint64(), ctx.Field, ctx.Value, ctx.SystemId)
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  修改状态
 */
func (service *AdminSpecialService) UpdateFieldByCodeId(ctx context.SpecialUpdateContext) bool {
	return adminSpecialMapper.UpdateFieldByCodeId(ctx.Id.Uint64(), ctx.Field, ctx.Value, ctx.SystemId)
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  修改状态
 */
func (service *AdminSpecialService) SaveUpdateSpecial(ctx context.SpecialSaveUpdateVo) (dbspecial *model.Special) {
	// 保存入库
	var special model.Special
	utils.CopyProperties(&special, ctx)
	parseUint, _ := strconv.ParseUint(ctx.Id, 10, 64)
	special.Id = parseUint
	if special.Id > 0 {
		pvo := adminSpecialMapper.GetSpecialByID(special.Id, ctx.SystemId)
		cacheKey := fmt.Sprintf("SYSTEM:SPECIAL:GetUserStudyDetailByPath:%s:%d", pvo.Path, ctx.SystemId)
		rdb.RdbDel(cacheKey)
	}
	data := adminSpecialMapper.SaveUpdateSpecial(special)
	return data
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  保存和修改兑换码
 */
func (service *AdminSpecialService) SaveUpdateCode(ctx context.SpecialCodeContext) *vo.SpecialCodeVO {
	// 保存入库
	var specialCode model.SpecialCode
	var specialVoCode vo.SpecialCodeVO
	utils.CopyProperties(&specialCode, ctx)
	parseUint, _ := strconv.ParseUint(ctx.Id, 10, 64)
	specialCode.Id = parseUint
	specialCode.Opid = ctx.Opid.Uint64()
	data := adminSpecialMapper.SaveUpdateSpecialCode(specialCode)
	utils.CopyProperties(&specialVoCode, data)
	return &specialVoCode
}

/**
 * @author feige
 * @date 2023-10-13
 * @version 1.0
 * @desc 查看兑换码
 */
func (service *AdminSpecialService) FindCodePage(ctx context.CodeSearchContext) *page.Page {
	p := adminSpecialMapper.FindSpecialCodePage(ctx)
	specialCodes := p.Records.([]model.SpecialCode)
	specialCodeVos := []vo.SpecialCodeVO{}
	for _, specialCode := range specialCodes {
		// 3: 查询当前登录的用户信息和资源id去查询用户资源收藏表
		specialCodeVo := vo.SpecialCodeVO{}
		utils.CopyProperties(&specialCodeVo, specialCode)
		// 2: 如果没有错误就必须把model数据导入vo数据中
		specialCodeVos = append(specialCodeVos, specialCodeVo)
	}
	p.Records = specialCodeVos
	return p
}

/**
 * 批量授权用户
 * @author feige
 * @date 2023-12-06
 * @version 1.0
 * @desc
 */
func (service *AdminSpecialService) SaveUserSepcialOrder(ctx context.BatchUsersContext) bool {
	// 1： 判断用户是否购买此小册，如果购买过了就就不要去保存订单
	userVo := userMapper.GetUserInfoByUuid(ctx.Uuid, ctx.SystemId)
	userId := userVo.Id
	// 1： 判断用户是否购买此专题，如果购买过了就就不要去保存订单
	isBuyFlag := userBuySpecialMapper.CountUserBuySpecialNo(userId, ctx.Opid.Uint64(), ctx.SystemId)
	if isBuyFlag == 0 {
		// 根据专题id查询专题信息
		special, _ := specialMapper.GetByIdTOPay(ctx.Opid.Uint64(), ctx.SystemId)
		userVo := userMapper.GetUserByID(userId, ctx.SystemId)

		userSpecialContext := model.UserBuySpecial{}
		OutTradeNo := service.GetSnowWorkerIdString(8)
		// 处理返回结果
		userSpecialContext.Opid = ctx.Opid.Uint64()
		userSpecialContext.Title = special.Title
		userSpecialContext.Cover = special.Img

		userSpecialContext.UserId = userId
		userSpecialContext.Username = userVo.Username
		userSpecialContext.Avatar = userVo.Avatar
		userSpecialContext.Uuid = userVo.Uuid
		userSpecialContext.Phone = userVo.Telephone
		userSpecialContext.Address = userVo.Address
		userSpecialContext.Nickname = userVo.Nickname

		userSpecialContext.Code = ""
		userSpecialContext.PayMethod = 4
		userSpecialContext.PayMethodName = "人工操作"
		userSpecialContext.Tradeno = OutTradeNo
		userSpecialContext.Orderno = OutTradeNo
		userSpecialContext.OrderJson = ""
		// 保存订单的接口
		userSpecialContext.SystemId = ctx.SystemId
		userSpecialContext.SystemName = ctx.SystemName
		userSpecialContext.Price = special.Price
		userBuySpecialMapper.SaveUserBuySpecial(userSpecialContext)

		// 保存消息
		messageMeContext := context3.MessageMeContext{}
		messageMeContext.UserId = userId
		messageMeContext.Title = special.Title
		messageMeContext.Uuid = userVo.Uuid
		messageMeContext.SystemId = ctx.SystemId
		messageMeContext.SystemName = "系统512"
		messageMeContext.Username = userVo.Nickname
		messageMeContext.Url = "https://www.study512.com/special/" + special.Path
		messageMeService.SaveMessageMeBuyResumeTemplate(&messageMeContext)
		return true
	} else {
		return false
	}
}

/**
 * @author feige
 * @date 2023-10-08
 * @desc 根据id查询资源信息，不包含内容
 */
func (service *AdminSpecialService) FindAdminSpecialBindsAll(specialId uint64, userId uint64, systemId uint64, flag bool) (pvos []*vo.SpecialBindVo, err error) {
	// 1: 根据id查询数据层
	specialBinds, _ := specialBindMapper.FindAdminSpecialBindsAll(specialId, systemId)
	specialBindVos := []*vo.SpecialBindVo{}
	for _, specialBind := range specialBinds {
		specialBindVo := vo.SpecialBindVo{}
		utils.CopyProperties(&specialBindVo, specialBind)
		details, _ := service.FindAdminSpecialBindsDetailAll(specialId, specialBind.Id, userId, systemId, specialBind.Type, flag)
		// 绑定明细
		specialBindVo.Children = details
		// 转换vo返回
		specialBindVos = append(specialBindVos, &specialBindVo)
	}
	return specialBindVos, nil
}

/**
 * @author feige
 * @date 2023-10-08
 * @desc 根据id查询资源信息，不包含内容
 */
func (service *AdminSpecialService) FindAdminSpecialBindsDetailAll(specialId uint64, bindId uint64, userId uint64, systemId uint64,
	stype int, flag bool) (pvos []*vo.SpecialBindDetailVo, err error) {
	// 1: 根据id查询数据层
	specialBindDetails, _ := specialBindMapper.FindAdminSpecialBindDetailsAll(specialId, bindId, systemId)
	specialBindDetailVos := []*vo.SpecialBindDetailVo{}
	for _, specialBindDetail := range specialBindDetails {
		specialBindDetailVo := vo.SpecialBindDetailVo{}
		utils.CopyProperties(&specialBindDetailVo, specialBindDetail)
		specialBindDetailVo.Id.Data = strconv.FormatUint(specialBindDetail.Id, 10)
		specialBindDetailVo.NoteId.Data = strconv.FormatUint(specialBindDetail.NoteId, 10)
		specialBindDetailVo.TeacherId.Data = strconv.FormatUint(specialBindDetail.TeacherId, 10)
		specialBindDetailVo.SpecialId.Data = strconv.FormatUint(specialBindDetail.SpecialId, 10)
		specialBindDetailVo.BindId.Data = strconv.FormatUint(specialBindDetail.BindId, 10)
		specialBindDetailVos = append(specialBindDetailVos, &specialBindDetailVo)
	}

	if len(specialBindDetailVos) > 0 {
		// 小册
		if stype == 1 {
			var noteIds []uint64
			for _, detailVo := range specialBindDetailVos {
				parseUint, _ := strconv.ParseUint(detailVo.NoteId.Data, 10, 64)
				noteIds = append(noteIds, parseUint)
			}
			specialBindDetailNewVos := []*vo.SpecialBindDetailVo{}
			noteList := noteMapper.FindNoteByIDS(noteIds)
			if len(noteList) > 0 {
				studyVos := []*nvo.NoteStudyVo{}
				if userId > 0 && flag {
					studyVos = noteMapper.CountNoteSpecialStudys(specialId, userId, systemId)
				}
				for _, detailVo := range specialBindDetailVos {
					for _, note := range noteList {
						if note.Id == detailVo.NoteId.Uint64() {
							specialBindDetailVo := vo.SpecialBindDetailVo{}
							utils.CopyProperties(&specialBindDetailVo, note)
							specialBindDetailVo.UpdateTime = note.UpdateTime
							specialBindDetailVo.Ntype = note.Ntype
							specialBindDetailVo.Userid.Data = strconv.FormatUint(note.Userid, 10)
							if userId > 0 && len(studyVos) > 0 && flag {
								for _, studyVo := range studyVos {
									if studyVo.NoteId == note.Id {
										specialBindDetailVo.Percent = studyVo.Percent
									}
								}
							}
							specialBindDetailVo.Id = detailVo.Id
							specialBindDetailVo.BindId = detailVo.BindId
							specialBindDetailVo.NoteId = detailVo.NoteId
							specialBindDetailVo.Sorted = detailVo.Sorted
							specialBindDetailVo.Status = detailVo.Status
							specialBindDetailNewVos = append(specialBindDetailNewVos, &specialBindDetailVo)

						}
					}
				}
			}
			return specialBindDetailNewVos, nil
		}

		// 老师
		if stype == 2 {
			var teacherIds []uint64
			for _, detailVo := range specialBindDetailVos {
				parseUint, _ := strconv.ParseUint(detailVo.TeacherId.Data, 10, 64)
				teacherIds = append(teacherIds, parseUint)
			}
			specialBindDetailNewVos := []*vo.SpecialBindDetailVo{}
			userList := userMapper.FindUserByIDS(teacherIds)
			for _, detailVo := range specialBindDetailVos {
				for _, user := range *userList {
					if user.Id == detailVo.TeacherId.Uint64() {
						specialBindDetailVo := vo.SpecialBindDetailVo{}
						utils.CopyProperties(&specialBindDetailVo, user)
						specialBindDetailVo.Id = detailVo.Id
						specialBindDetailVo.Title = user.Nickname
						specialBindDetailVo.Userid = detailVo.TeacherId
						specialBindDetailVo.BindId = detailVo.BindId
						specialBindDetailVo.Sorted = detailVo.Sorted
						specialBindDetailVo.Status = detailVo.Status
						specialBindDetailVo.Nickname = user.Nickname
						specialBindDetailVo.Username = user.Username
						specialBindDetailVo.Description = user.Job
						specialBindDetailVo.Avatar = user.Avatar
						specialBindDetailVo.Uuid = user.Uuid
						specialBindDetailVo.TeacherIntro = user.Intro
						specialBindDetailNewVos = append(specialBindDetailNewVos, &specialBindDetailVo)
					}
				}
			}
			return specialBindDetailNewVos, nil
		}
	}

	return nil, nil
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据id删除
 */
func (service *AdminSpecialService) DelById(id uint64, systemId uint64) bool {
	return adminSpecialMapper.DelById(id, systemId)
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据用户id查询用户明细
 */
func (service *AdminSpecialService) DelCodeById(id uint64, systemId uint64) bool {
	return adminSpecialMapper.DelCodeById(id, systemId)
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据用户id查询用户明细
 */
func (service *AdminSpecialService) DelByUserOrderId(id uint64, systemId uint64) bool {
	return adminSpecialMapper.DelByUserorderId(id, systemId)
}

/*
复制
*
*/
func (service *AdminSpecialService) CopyData(id uint64, systemId uint64) bool {
	// 保存入库
	data := adminSpecialMapper.GetById(id, systemId)
	data.Id = 0
	data.Status = 0
	data.CreateTime = time.Now()
	data.UpdateTime = time.Now()
	adminSpecialMapper.SaveUpdateSpecial(*data)
	return true
}
